package models

import (
	"encoding/json"
	"fmt"
	"hytx_manager/pkg/aliyun"
	"hytx_manager/pkg/util"
	"time"
)

type SMSValidate struct {
	ID int
	Type int
	MobilePhone string
	DeadLine time.Time
	MsgCode string
	IsValided int
	IsSended int
	TempId string
	Data string
	ResultInfo string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (s *SMSValidate) TableName () string {
	return "sms_validate"
}

func NewSMSValidate (phone string) *SMSValidate {
	return &SMSValidate{
		MobilePhone : phone,
	}
}
//验证手机号是否发送太频繁
func (s *SMSValidate) IsFrequently() bool {
	sms := s.getSMSByPhone()
	if sms.DeadLine.After(time.Now()) && sms.DeadLine.Unix() - time.Now().Unix() < 300 {
		return true
	}
	return false
}
//发送短信
func (s *SMSValidate) SendSMS(typ int) bool {
	code := util.SixVerificationCode()
	res, err := aliyun.SMSsend(s.MobilePhone, code)
	if err != nil {
		return false
	}
	s.Type = typ
	mm ,_ := time.ParseDuration("5m")
	s.DeadLine = time.Now().Add(mm)
	s.MsgCode = code
	type j struct{
		Message string `json:"Message"`
		RequestId string `json:"RequestId"`
		BizId string `json:"BizId"`
		Code string `json:"Code"`
	}
	js := &j{}
	json.Unmarshal([]byte(res), js)
	if js.Code == "OK" {
		s.IsSended = 1
	}else{
		s.IsSended = 0
	}
	s.IsValided = 0
	s.TempId = "SMS_117290028"
	s.Data = fmt.Sprintf("{\"code\":\"%s\"}", code)
	s.ResultInfo = res
	s.CreatedAt = time.Now()
	err = DB.Model(s).Create(s).Error
	if err != nil {
		return false
	}
	if js.Code != "OK" {
		return false
	}
	return true
}

func (s *SMSValidate) getSMSByPhone() *SMSValidate{
	var sms SMSValidate
	err := DB.Table("sms_validate").Where("mobile_phone=?", s.MobilePhone).First(&sms).Error
	if err != nil{
		return nil
	}
	return &sms
}

func (s *SMSValidate) ValidateSMS(code string) bool {
	var res SMSValidate
	err := DB.Table("sms_validate").Where("mobile_phone=?",s.MobilePhone).Where("is_sended=1").Where("is_valided=0").Where("msg_code=?",code).First(&res).Error
	if err != nil {
		return false
	}
	if res.DeadLine.Before(time.Now()) {
		return false
	}
	DB.Table("sms_validate").Where("id=?", res.ID).Update("is_valided", 1)
	return true
}